<template>
  <div class="exam-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">考试中心</h1>
        <p class="page-subtitle">在线考试，检验学习成果</p>
      </div>
    </div>
    
    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-content">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索考试名称、科目..."
            size="large"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 筛选器 -->
        <div class="filters">
          <el-select
            v-model="filters.category"
            placeholder="考试类型"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部类型" value="" />
            <el-option label="课程考试" value="course" />
            <el-option label="模拟考试" value="mock" />
            <el-option label="认证考试" value="certification" />
            <el-option label="竞赛考试" value="competition" />
          </el-select>
          
          <el-select
            v-model="filters.status"
            placeholder="考试状态"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部状态" value="" />
            <el-option label="未开始" value="upcoming" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="finished" />
          </el-select>
          
          <el-select
            v-model="filters.difficulty"
            placeholder="难度等级"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部难度" value="" />
            <el-option label="入门" value="beginner" />
            <el-option label="进阶" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>
          
          <el-select
            v-model="sortBy"
            placeholder="排序方式"
            @change="handleSortChange"
          >
            <el-option label="最新发布" value="latest" />
            <el-option label="考试时间" value="examTime" />
            <el-option label="参与人数" value="participants" />
            <el-option label="难度等级" value="difficulty" />
          </el-select>
        </div>
      </div>
    </div>
    
    <!-- 考试统计 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon color="#409eff"><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalExams }}</div>
            <div class="stat-label">总考试数</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon color="#67c23a"><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.completedExams }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon color="#e6a23c"><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.ongoingExams }}</div>
            <div class="stat-label">进行中</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon">
            <el-icon color="#f56c6c"><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.averageScore }}%</div>
            <div class="stat-label">平均分</div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 考试列表 -->
    <div class="exam-content">
      <div class="content-header">
        <div class="view-toggle">
          <el-radio-group v-model="viewMode" @change="handleViewModeChange">
            <el-radio-button label="grid">
              <el-icon><Grid /></el-icon>
              卡片视图
            </el-radio-button>
            <el-radio-button label="list">
              <el-icon><List /></el-icon>
              列表视图
            </el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="result-info">
          共找到 {{ total }} 个考试
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="examList.length === 0" class="empty-state">
        <el-empty description="暂无考试数据">
          <el-button type="primary" @click="resetFilters">重置筛选</el-button>
        </el-empty>
      </div>
      
      <!-- 卡片视图 -->
      <div v-else-if="viewMode === 'grid'" class="exam-grid">
        <div
          v-for="exam in examList"
          :key="exam.id"
          class="exam-card"
          @click="handleExamClick(exam)"
        >
          <div class="card-header">
            <div class="exam-category">
              <el-tag
                :type="getCategoryType(exam.category)"
                size="small"
                effect="plain"
              >
                {{ getCategoryText(exam.category) }}
              </el-tag>
            </div>
            
            <div class="exam-status">
              <el-tag
                :type="getStatusType(exam.status)"
                size="small"
              >
                {{ getStatusText(exam.status) }}
              </el-tag>
            </div>
          </div>
          
          <div class="card-content">
            <h3 class="exam-title">{{ exam.title }}</h3>
            <p class="exam-description">{{ exam.description }}</p>
            
            <div class="exam-meta">
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>{{ exam.duration }}分钟</span>
              </div>
              
              <div class="meta-item">
                <el-icon><Document /></el-icon>
                <span>{{ exam.questionCount }}题</span>
              </div>
              
              <div class="meta-item">
                <el-icon><User /></el-icon>
                <span>{{ formatNumber(exam.participants) }}人参与</span>
              </div>
            </div>
            
            <div class="exam-time">
              <div class="time-item">
                <span class="time-label">开始时间：</span>
                <span class="time-value">{{ formatDateTime(exam.startTime) }}</span>
              </div>
              <div class="time-item">
                <span class="time-label">结束时间：</span>
                <span class="time-value">{{ formatDateTime(exam.endTime) }}</span>
              </div>
            </div>
            
            <div class="exam-difficulty">
              <el-tag
                :type="getDifficultyType(exam.difficulty)"
                size="small"
                effect="plain"
              >
                {{ getDifficultyText(exam.difficulty) }}
              </el-tag>
            </div>
          </div>
          
          <div class="card-footer">
            <div class="exam-score" v-if="exam.score !== null">
              <span class="score-label">我的成绩：</span>
              <span class="score-value" :class="getScoreClass(exam.score)">
                {{ exam.score }}分
              </span>
            </div>
            
            <div class="exam-actions">
              <el-button
                v-if="exam.status === 'upcoming'"
                type="primary"
                size="small"
                @click.stop="handleStartExam(exam)"
                :disabled="!canStartExam(exam)"
              >
                {{ getExamButtonText(exam) }}
              </el-button>
              
              <el-button
                v-else-if="exam.status === 'ongoing'"
                type="success"
                size="small"
                @click.stop="handleContinueExam(exam)"
              >
                继续考试
              </el-button>
              
              <el-button
                v-else
                type="info"
                size="small"
                plain
                @click.stop="handleViewResult(exam)"
              >
                查看结果
              </el-button>
              
              <el-button
                size="small"
                plain
                @click.stop="handleViewDetail(exam)"
              >
                详情
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 列表视图 -->
      <div v-else class="exam-table">
        <el-table
          :data="examList"
          stripe
          @row-click="handleExamClick"
          style="width: 100%"
        >
          <el-table-column prop="title" label="考试名称" min-width="200">
            <template #default="{ row }">
              <div class="exam-title-cell">
                <div class="title">{{ row.title }}</div>
                <div class="description">{{ row.description }}</div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="category" label="类型" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getCategoryType(row.category)"
                size="small"
                effect="plain"
              >
                {{ getCategoryText(row.category) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="difficulty" label="难度" width="80">
            <template #default="{ row }">
              <el-tag
                :type="getDifficultyType(row.difficulty)"
                size="small"
                effect="plain"
              >
                {{ getDifficultyText(row.difficulty) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="duration" label="时长" width="80">
            <template #default="{ row }">
              {{ row.duration }}分钟
            </template>
          </el-table-column>
          
          <el-table-column prop="questionCount" label="题数" width="80">
            <template #default="{ row }">
              {{ row.questionCount }}题
            </template>
          </el-table-column>
          
          <el-table-column prop="startTime" label="开始时间" width="150">
            <template #default="{ row }">
              {{ formatDateTime(row.startTime) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getStatusType(row.status)"
                size="small"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="score" label="成绩" width="80">
            <template #default="{ row }">
              <span
                v-if="row.score !== null"
                :class="getScoreClass(row.score)"
              >
                {{ row.score }}分
              </span>
              <span v-else class="no-score">-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="table-actions">
                <el-button
                  v-if="row.status === 'upcoming'"
                  type="primary"
                  size="small"
                  @click.stop="handleStartExam(row)"
                  :disabled="!canStartExam(row)"
                >
                  {{ getExamButtonText(row) }}
                </el-button>
                
                <el-button
                  v-else-if="row.status === 'ongoing'"
                  type="success"
                  size="small"
                  @click.stop="handleContinueExam(row)"
                >
                  继续
                </el-button>
                
                <el-button
                  v-else
                  type="info"
                  size="small"
                  plain
                  @click.stop="handleViewResult(row)"
                >
                  结果
                </el-button>
                
                <el-button
                  size="small"
                  plain
                  @click.stop="handleViewDetail(row)"
                >
                  详情
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
  Search,
  Document,
  CircleCheck,
  Clock,
  TrendCharts,
  Grid,
  List,
  User
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getExamList, getExamStats } from '@/api/exam'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const searchQuery = ref('')
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const sortBy = ref('latest')

const filters = ref({
  category: '',
  status: '',
  difficulty: ''
})

const examList = ref([])
const stats = ref({
  totalExams: 0,
  completedExams: 0,
  ongoingExams: 0,
  averageScore: 0
})

// 计算属性
const searchDebounced = computed(() => {
  // 防抖搜索
  return searchQuery.value
})

// 方法
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getCategoryType = (category) => {
  const types = {
    course: 'primary',
    mock: 'success',
    certification: 'warning',
    competition: 'danger'
  }
  return types[category] || 'info'
}

const getCategoryText = (category) => {
  const texts = {
    course: '课程考试',
    mock: '模拟考试',
    certification: '认证考试',
    competition: '竞赛考试'
  }
  return texts[category] || '其他'
}

const getStatusType = (status) => {
  const types = {
    upcoming: 'info',
    ongoing: 'warning',
    finished: 'success'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    upcoming: '未开始',
    ongoing: '进行中',
    finished: '已结束'
  }
  return texts[status] || '未知'
}

const getDifficultyType = (difficulty) => {
  const types = {
    beginner: 'success',
    intermediate: 'warning',
    advanced: 'danger'
  }
  return types[difficulty] || 'info'
}

const getDifficultyText = (difficulty) => {
  const texts = {
    beginner: '入门',
    intermediate: '进阶',
    advanced: '高级'
  }
  return texts[difficulty] || '未知'
}

const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

const canStartExam = (exam) => {
  const now = new Date()
  const startTime = new Date(exam.startTime)
  return now >= startTime
}

const getExamButtonText = (exam) => {
  if (!canStartExam(exam)) {
    return '未到时间'
  }
  return '开始考试'
}

// 事件处理
const handleSearch = () => {
  currentPage.value = 1
  loadExamList()
}

const handleFilterChange = () => {
  currentPage.value = 1
  loadExamList()
}

const handleSortChange = () => {
  currentPage.value = 1
  loadExamList()
}

const handleViewModeChange = () => {
  // 视图模式切换
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadExamList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadExamList()
}

const resetFilters = () => {
  searchQuery.value = ''
  filters.value = {
    category: '',
    status: '',
    difficulty: ''
  }
  sortBy.value = 'latest'
  currentPage.value = 1
  loadExamList()
}

const handleExamClick = (exam) => {
  router.push(`/exam/${exam.id}`)
}

const handleStartExam = async (exam) => {
  if (!canStartExam(exam)) {
    ElMessage.warning('考试尚未开始')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要开始考试「${exam.title}」吗？\n考试时长：${exam.duration}分钟\n题目数量：${exam.questionCount}题`,
      '开始考试',
      {
        confirmButtonText: '开始',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    router.push(`/exam/${exam.id}/take`)
  } catch {
    // 用户取消
  }
}

const handleContinueExam = (exam) => {
  router.push(`/exam/${exam.id}/take`)
}

const handleViewResult = (exam) => {
  router.push(`/exam/${exam.id}/result`)
}

const handleViewDetail = (exam) => {
  router.push(`/exam/${exam.id}`)
}

// 数据加载
const loadExamList = async () => {
  try {
    loading.value = true
    
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value,
      sortBy: sortBy.value,
      ...filters.value
    }
    
    const response = await getExamList(params)
    examList.value = response.data.list
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('加载考试列表失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await getExamStats()
    stats.value = response.data
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 监听器
watch(searchDebounced, () => {
  handleSearch()
}, { debounce: 500 })

// 生命周期
onMounted(() => {
  loadExamList()
  loadStats()
})
</script>

<style lang="scss" scoped>
.exam-list {
  min-height: 100vh;
  background: var(--bg-color);
}

.page-header {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-color-dark) 100%);
  color: white;
  padding: var(--spacing-xl) 0;
  text-align: center;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-lg);
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 var(--spacing-md) 0;
}

.page-subtitle {
  font-size: var(--font-size-large);
  opacity: 0.9;
  margin: 0;
}

.filter-section {
  background: white;
  border-bottom: 1px solid var(--border-color-extra-light);
  padding: var(--spacing-lg) 0;
}

.filter-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-lg);
  display: flex;
  gap: var(--spacing-lg);
  align-items: center;
}

.search-box {
  flex: 1;
  max-width: 400px;
}

.filters {
  display: flex;
  gap: var(--spacing-md);
  
  .el-select {
    width: 120px;
  }
}

.stats-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: var(--spacing-lg);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--spacing-lg);
}

.stat-card {
  background: white;
  border-radius: var(--border-radius-base);
  box-shadow: var(--box-shadow-light);
  padding: var(--spacing-lg);
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  transition: var(--transition-all);
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: var(--box-shadow-base);
  }
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: var(--fill-color-extra-light);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .el-icon {
    font-size: 24px;
  }
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-color-primary);
  line-height: 1;
  margin-bottom: var(--spacing-xs);
}

.stat-label {
  font-size: var(--font-size-small);
  color: var(--text-color-secondary);
}

.exam-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-lg) var(--spacing-xl);
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
}

.view-toggle {
  :deep(.el-radio-button__inner) {
    display: flex;
    align-items: center;
    gap: var(--spacing-xs);
  }
}

.result-info {
  color: var(--text-color-secondary);
  font-size: var(--font-size-small);
}

.loading-container {
  background: white;
  border-radius: var(--border-radius-base);
  box-shadow: var(--box-shadow-light);
  padding: var(--spacing-lg);
}

.empty-state {
  background: white;
  border-radius: var(--border-radius-base);
  box-shadow: var(--box-shadow-light);
  padding: var(--spacing-xl);
  text-align: center;
}

.exam-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: var(--spacing-lg);
}

.exam-card {
  background: white;
  border-radius: var(--border-radius-base);
  box-shadow: var(--box-shadow-light);
  overflow: hidden;
  transition: var(--transition-all);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-md) var(--spacing-lg);
  background: var(--fill-color-extra-light);
  border-bottom: 1px solid var(--border-color-extra-light);
}

.card-content {
  padding: var(--spacing-lg);
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.exam-title {
  font-size: var(--font-size-medium);
  font-weight: 600;
  color: var(--text-color-primary);
  line-height: 1.4;
  margin: 0;
  @include text-ellipsis-multi(2);
}

.exam-description {
  font-size: var(--font-size-small);
  color: var(--text-color-secondary);
  line-height: 1.5;
  margin: 0;
  @include text-ellipsis-multi(2);
}

.exam-meta {
  display: flex;
  gap: var(--spacing-md);
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-small);
  color: var(--text-color-secondary);
  
  .el-icon {
    font-size: 14px;
  }
}

.exam-time {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.time-item {
  display: flex;
  font-size: var(--font-size-small);
  
  .time-label {
    color: var(--text-color-secondary);
    min-width: 70px;
  }
  
  .time-value {
    color: var(--text-color-primary);
  }
}

.card-footer {
  padding: var(--spacing-md) var(--spacing-lg);
  border-top: 1px solid var(--border-color-extra-light);
  background: var(--fill-color-extra-light);
}

.exam-score {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  margin-bottom: var(--spacing-md);
  
  .score-label {
    font-size: var(--font-size-small);
    color: var(--text-color-secondary);
  }
  
  .score-value {
    font-weight: 600;
    font-size: var(--font-size-base);
    
    &.score-excellent {
      color: var(--success-color);
    }
    
    &.score-good {
      color: var(--primary-color);
    }
    
    &.score-pass {
      color: var(--warning-color);
    }
    
    &.score-fail {
      color: var(--danger-color);
    }
  }
}

.exam-actions {
  display: flex;
  gap: var(--spacing-sm);
}

.exam-table {
  background: white;
  border-radius: var(--border-radius-base);
  box-shadow: var(--box-shadow-light);
  overflow: hidden;
  
  :deep(.el-table) {
    .exam-title-cell {
      .title {
        font-weight: 600;
        color: var(--text-color-primary);
        margin-bottom: var(--spacing-xs);
      }
      
      .description {
        font-size: var(--font-size-small);
        color: var(--text-color-secondary);
        @include text-ellipsis;
      }
    }
    
    .score-excellent {
      color: var(--success-color);
      font-weight: 600;
    }
    
    .score-good {
      color: var(--primary-color);
      font-weight: 600;
    }
    
    .score-pass {
      color: var(--warning-color);
      font-weight: 600;
    }
    
    .score-fail {
      color: var(--danger-color);
      font-weight: 600;
    }
    
    .no-score {
      color: var(--text-color-placeholder);
    }
    
    .table-actions {
      display: flex;
      gap: var(--spacing-xs);
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: var(--spacing-xl);
}

// 响应式设计
@include respond-below(lg) {
  .filter-content {
    flex-direction: column;
    gap: var(--spacing-md);
    
    .search-box {
      max-width: none;
      width: 100%;
    }
    
    .filters {
      width: 100%;
      justify-content: space-between;
      
      .el-select {
        flex: 1;
        min-width: 100px;
      }
    }
  }
  
  .content-header {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
  
  .exam-grid {
    grid-template-columns: 1fr;
  }
}

@include respond-below(md) {
  .page-title {
    font-size: 2rem;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .filters {
    flex-direction: column;
    
    .el-select {
      width: 100%;
    }
  }
  
  .exam-card {
    .card-content {
      padding: var(--spacing-md);
    }
    
    .card-footer {
      padding: var(--spacing-sm) var(--spacing-md);
    }
  }
  
  .exam-actions {
    flex-direction: column;
  }
}

@include respond-below(sm) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .exam-meta {
    flex-direction: column;
    gap: var(--spacing-sm);
  }
}
</style>